package com.example.project.activity.tubiao;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;

import com.example.project.activity.jizhang.RecordActivity;
import com.example.project.activity.mingxi.MainActivity;
import com.example.project.activity.wode.WdActivity;
import com.example.project.adapter.ChartItemAdapter;
import com.example.project.bean.ChartItemBean;

import com.example.project.bean.YearDetail;
import com.example.project.utils.DateUtil;
import com.example.project.utils.MonPickerDialog;
import com.example.project.utils.YearPickerDialog;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//图表页面
public class MonthChartActivity extends AppCompatActivity implements View.OnClickListener {
    private List<String> spinnerlist = new ArrayList<String>(); //下拉列表数据
    private TextView textview,time;
    private Spinner spinnertext; //下拉列表
    private ArrayAdapter<String> adapter;

    private AlertDialog alertDialog; //单选框
    private ImageView Ivjz, Ivbb, Ivzj, Ivwd; //下方跳转的控件
    private TextView tv_bb; //下方跳转的控件的文字
    Button inBtn, outBtn; //输入按钮，输出按钮
    TextView dateTv, inTv, outTv; //账单时间，收入账单，支出账单
    ListView list_tb; //图表list

    int month, year, date;  //int年月日
    String months, years, dates; //string年月日
    int selectTime = 1; //查询的  ，时间(年：0，月：1)
    int selectChart = 0; //0饼状图，1折现图
    int mainId; //用户
    Calendar calendar; //日历控件
    LineChart lineChart; //折线图控件
    PieChart mPieChart; //饼状图控件
    ChartItemAdapter chartItemAdapter;//适配器
    List<ChartItemBean> chartItemBeans = new ArrayList<>();//声明数据源
    boolean start=true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_month_chart);
        initView(); /** 初始化控件*/
    }

    @Override
    protected void onStart() {
        super.onStart();
        initTime(); /** 获取时间*/
        initspinner(); //下拉列表
        ListItem();
//        lineChartInManager(null);
//        initData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        time=findViewById(R.id.chart_tv_date);
        lineChart=findViewById(R.id.linechart);
        mPieChart = findViewById(R.id.mPieChart);
        mainId = MyApplication.getMainId();
        inBtn = findViewById(R.id.chart_btn_in);
        outBtn = findViewById(R.id.chart_btn_out);
        dateTv = findViewById(R.id.chart_tv_date);
        inTv = findViewById(R.id.chart_tv_in);
        outTv = findViewById(R.id.chart_tv_out);
        list_tb = findViewById(R.id.list_tb);

        Ivjz = findViewById(R.id.Iv_jz);
        Ivjz.setOnClickListener(this);
        Ivbb = findViewById(R.id.Iv_bb);
        Ivbb.setOnClickListener(this);
        Ivzj = findViewById(R.id.Iv_zj);
        Ivzj.setOnClickListener(this);
        Ivwd = findViewById(R.id.Iv_wd);
        Ivwd.setOnClickListener(this);
        tv_bb = findViewById(R.id.tv_bb);
        Ivbb.setImageResource(R.drawable.bbb);
        tv_bb.setTextColor(Color.parseColor("#87CEFA"));
        spinnertext = (Spinner) findViewById(R.id.spinner1);
        textview = (TextView) findViewById(R.id.textView1);
    }


    /** 获取时间的方法*/
    private void initTime() {
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        date =calendar.get(Calendar.DATE);
        textview.setText(year+"-"+month);
        years=String.valueOf( year );
        months=String.valueOf( month );
        String mainIds=String.valueOf( mainId );
        time.setText(year+"年"+month+"月账单");
        //初始化本月支出数据
        volleyMonthInfoOne(years, months,mainIds);
        volleyMonthInfoTwo(years,months,"0",mainIds);
        volleyMonthInfoThree(years,months, "0",mainIds);
    }

    /**
     * 初始化下拉列表
     */
    private void initspinner(){
        spinnerlist.add("年");
        spinnerlist.add("月");

        //第二步：为下拉列表定义一个适配器
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerlist);
        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        spinnertext.setAdapter(adapter);
        //第五步：添加监听器，为下拉列表设置事件的响应
        spinnertext.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            //选择列表项的操作
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                /* 将所选spinnertext的值带入myTextView中*/
                System.out.println("position:"+position);
                if (!start){
                    if (position==0 ){
                        selectYearTime();
                    }else if(position==1){
                        selectMonthTime();
                    }
                    parent.setVisibility(View.VISIBLE);
                }
                start=false;
                /* 将 spinnertext 显示^*/

            }
            //未选中时候的操作
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
//               textview.setText("NONE");
                parent.setVisibility(View.VISIBLE);
            }
        });

        //将spinnertext添加到OnTouchListener对内容选项触屏事件处理
        spinnertext.setOnTouchListener(new Spinner.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //二次点击同一item无响应事件
                //最简单的就是把他们改成初始值
                //那么这里我们就需要使用放射的机制来达到这个目的。
                try {
                    Class<?> clazz = AdapterView.class;
                    Field field = clazz.getDeclaredField("mOldSelectedPosition");
                    field.setAccessible(true);
                    field.setInt(spinnertext,AdapterView.INVALID_POSITION);
                } catch(Exception e){
                    e.printStackTrace();
                }
                return false;
            }
        });

        //焦点改变事件处理
        spinnertext.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                v.setVisibility(View.VISIBLE);
                Log.i("spinner", "Spinner FocusChange事件被触发！");
            }
        });
    }

    //显示年-月份框
    private void selectMonthTime() {
        new MonPickerDialog(MonthChartActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                selectTime = 1;
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                textview.setText(DateUtil.clanderTodatetime(calendar, "yyyy-MM"));
                years=String.valueOf( year );
                month=month+1;
                months=String.valueOf( month );
                String mainIds=String.valueOf( mainId );
                String time =year+"年"+month+"月账单";
                System.out.println("日期："+year+"-"+month+"-"+date);
                dateTv.setText(time);
                volleyMonthInfoOne(years, months,mainIds);
                volleyMonthInfoTwo(years,months,"0",mainIds);
                volleyMonthInfoThree(years,months, "0",mainIds);

            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)).show();
    }

    //显示年份框
    private void selectYearTime() {

        new YearPickerDialog(MonthChartActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                selectTime = 0;
                calendar.set(Calendar.YEAR, year);
//                calendar.set(Calendar.MONTH, monthOfYear);
                textview.setText(DateUtil.clanderTodatetime(calendar, "yyyy"));
                years=String.valueOf( year );
                String mainIds=String.valueOf( mainId );
                String time =year+"年账单";
                dateTv.setText(time);
                volleyMonthInfoOne(years,"",mainIds);
                volleyMonthInfoTwo(years,"","0",mainIds);
                volleyMonthInfoThree(years, "","0",mainIds);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)).show();
    }

    /* 设置按钮样式的改变  支出-0  收入-1*/
    private void setButtonStyle(int kind){
        if (kind == 0) {
            outBtn.setBackgroundResource( R.drawable.main_recordbtn_bg);
            outBtn.setTextColor(Color.WHITE);
            inBtn.setBackgroundResource( R.drawable.dialog_btn_bg);
            inBtn.setTextColor(Color.BLACK);

            String time=textview.getText().toString();
            if(time.length() > 4){
                String[] array=time.split("-");
                years=array[0];
                months=array[1];
            }else{
                years=time;
                months="";
            }
            System.out.println("年"+year+"月"+months);
            String mainIds=String.valueOf( mainId );
            if( selectTime == 0){
                volleyMonthInfoTwo(years, "", "0",mainIds);
                volleyMonthInfoThree(years,"", "0",mainIds);

            }else {
                volleyMonthInfoTwo(years, months, "0",mainIds);
                volleyMonthInfoThree(years,months, "0",mainIds);
            }


        }else if (kind == 1){

            inBtn.setBackgroundResource( R.drawable.main_recordbtn_bg);
            inBtn.setTextColor(Color.WHITE);
            outBtn.setBackgroundResource( R.drawable.dialog_btn_bg);
            outBtn.setTextColor(Color.BLACK);

            String time=textview.getText().toString();
            if(time.length() > 4){
                String[] array=time.split("-");
                years=array[0];
                months=array[1];
            }else{
                years=time;
                months="";
            }
            System.out.println("年"+year+"月"+months);
            String mainIds=String.valueOf( mainId );
            if( selectTime == 0){
                volleyMonthInfoTwo(years, "0", "1",mainIds);
                volleyMonthInfoThree(years,"", "1",mainIds);
            }else {
                volleyMonthInfoTwo(years, months, "1",mainIds);
                volleyMonthInfoThree(years, months,"1",mainIds);
            }
        }
    }

    //点击事件
    public void onClick(View view) {
        Intent intent=null;
        switch (view.getId()) {
            case R.id.chart_iv_rili:
                if(selectChart == 0){
                    selectChart=1;
                    mPieChart.setVisibility(mPieChart.GONE);
                    lineChart.setVisibility(lineChart.VISIBLE);
                }else{
                    selectChart=0;
                    mPieChart.setVisibility(mPieChart.VISIBLE);
                    lineChart.setVisibility(lineChart.GONE);
                }
                break;
            case R.id.chart_btn_in:
//                setone();
                //切换到收入操作
                setButtonStyle(1);
                break;
            case R.id.chart_btn_out:
//                settwo();
                //切换到支出操作
                setButtonStyle(0);
                break;
            case R.id.Iv_jz:
                intent=new Intent(this, MainActivity.class);
                startActivity( intent );
                break;
            case R.id.Iv_zj:
                intent=new Intent(this, RecordActivity.class);
                startActivity( intent );
                break;
            case R.id.Iv_wd:
                intent=new Intent(this, WdActivity.class);
                startActivity( intent );
                break;
        }
    }

    /* 统计某年某月的收支情况数据 （记账总条数,记账总钱数）*/
    private void volleyMonthInfoOne(String year,String month,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "MONTHInfo", Params.MonthList(year,month,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) {
                System.out.println("数据:"+jsonStr);
                JSONObject jsonObject = null;
                try {
                    jsonObject =new JSONObject( jsonStr );
                    String inrow=jsonObject.getString( "inrow" );
                    String outrow=jsonObject.getString( "outrow" );
                    String inMoney=jsonObject.getString( "inMoney" );
                    String outMoney=jsonObject.getString( "outMoney" );
                    inTv.setText("共"+inrow+"笔收入, ￥ "+inMoney);
                    outTv.setText("共"+outrow+"笔支出, ￥ "+outMoney);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthChartActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    /* 统计某年某月的收支情况数据 （记账名字和金额key-value）饼状图*/
    private void volleyMonthInfoTwo(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.Bill, "Bill", Params.MonthList(year,month,kind,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                List<HashMap<String, Object>> dataList;
                dataList = new ArrayList<>();
                JSONObject json = new JSONObject(jsonStr);
                JSONArray feedsArray = json.getJSONArray("data");
                if(feedsArray==null || feedsArray.equals("")){
                    if(kind.equals("1")){
                        Toast.makeText(MonthChartActivity.this, "暂无收入信息", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(MonthChartActivity.this, "暂无支出信息", Toast.LENGTH_LONG).show();
                    }
                    return;
                }
                for (int i = 0; i < feedsArray.length(); i++) {
                    JSONObject json2 = feedsArray.getJSONObject(i);
                    String name=json2.getString("name");
                    String money=json2.getString("money");
                    String sImageId=json2.getString("sImageId");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", name);
                    map.put("money", money);
                    map.put("sImageId", sImageId);
                    dataList.add(map);
                }
                System.out.println("饼状图:"+dataList);

                String kind=json.getString("message");
                if(kind.equals("收入账单")){
                    //收入账单
                    settwo(dataList);
                }else {
                    //支出账单
                    setone(dataList);
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthChartActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    /* 统计某年某月的收支情况数据 （记账年或月和金额key-value）折现图*/
    private void volleyMonthInfoThree(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.LineChart, "LineChart", Params.MonthMax(year,month,kind,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                List<HashMap<String, Object>> dataList;
                dataList = new ArrayList<>();
                JSONObject json = new JSONObject(jsonStr);
                JSONArray feedsArray = json.getJSONArray("data");
                if(feedsArray==null || feedsArray.equals("")){
                    if(kind.equals("1")){
                        Toast.makeText(MonthChartActivity.this, "暂无收入信息", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MonthChartActivity.this, "暂无支出信息", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                String time = null;
                for (int i = 0; i < feedsArray.length(); i++) {
                    JSONObject json2 = feedsArray.getJSONObject(i);
                    if(json2.has("month")){ //判断字段是否存在，存在就为true
                        String month=json2.getString("month");
                        String money=json2.getString("money");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("month", month);
                        map.put("money", money);
                        dataList.add(map);
                        time="month";
                    }
                    if(json2.has("day")){
                        String day=json2.getString("day");
                        String money=json2.getString("money");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("day", day);
                        map.put("money", money);
                        dataList.add(map);
                        time="day";
                    }

                }
                System.out.println("折线图数据:"+dataList);
                String kind=json.getString("message");
                if(kind.equals("收入账单")){
                    initData(dataList,time);
                }else {
                    initData(dataList,time);
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MonthChartActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //支出年，月扇形图
    private void setone(List<HashMap<String, Object>> hashMapList){
        /*折线饼状图*/
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //是否设置中心文字
        mPieChart.setDrawCenterText(true);
        //绘制中间文字
        SpannableString sp = new SpannableString("支出");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //图表数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        //详细数据
        ArrayList<ChartItemBean> chartItemBeanArrayList = new ArrayList<>();

        //总钱数
        float num=0;
        for(int i=0;i<hashMapList.size();i++){
            Map<String,Object> map = hashMapList.get(i);
            num =Float.parseFloat(map.get("money").toString() )+ num;
        }
        if(hashMapList.size()>7){
            for(int i=0;i<7;i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }else {
            for(int i=0;i<hashMapList.size();i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }
        getList(chartItemBeans);
        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLUE);
        mPieChart.setEntryLabelTextSize(18f);

        mPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {

            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }
            //整体扇形的监听
            @Override
            public void onNothingSelected() {

            }
        });

    }

    //收入年，月扇形图
    private void settwo(List<HashMap<String, Object>> hashMapList){
        /*折线饼状图*/
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //是否设置中心文字
        mPieChart.setDrawCenterText(true);
        //绘制中间文字
        SpannableString sp = new SpannableString("收入");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        //详细数据
        ArrayList<ChartItemBean> chartItemBeanArrayList = new ArrayList<>();

        //总钱数
        float num=0;
        for(int i=0;i<hashMapList.size();i++){
            Map<String,Object> map = hashMapList.get(i);
            num =Float.parseFloat(map.get("money").toString() )+ num;
        }
        if(hashMapList.size()>7){
            for(int i=0;i<7;i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }else {
            for(int i=0;i<hashMapList.size();i++){
                ChartItemBean chartItemBean = new ChartItemBean();
                Map<String,Object> map = hashMapList.get(i);
                chartItemBean.setsImageId(Integer.parseInt(map.get("sImageId").toString()) );
                chartItemBean.setType((map.get("name").toString()));
                chartItemBean.setTotalMoney(Float.parseFloat(map.get("money").toString() ));
                chartItemBean.setRatio(Float.parseFloat(map.get("money").toString())/num );
                chartItemBeanArrayList.add(chartItemBean);
                chartItemBeans.clear(); //清楚列表信息
                chartItemBeans.addAll(chartItemBeanArrayList); //将信息添加到列表里
                entries.add(new PieEntry(Float.parseFloat(map.get("money").toString()),map.get("name").toString()));
            }
        }
        getList(chartItemBeans);

        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLUE);
        mPieChart.setEntryLabelTextSize(18f);

    }


    //设置日x轴
    private void setDayXAxis(){
        XAxis xAxis = lineChart.getXAxis(); //获取x轴
        xAxis.setAxisMinimum(0f); //设置最小值
        xAxis.setAxisMaximum(31);  //设置最大值
        xAxis.setLabelCount(15); //设置显示个数
        xAxis.setDrawGridLines(false); //设置是否显示网格线
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //所在的位置
    }
    //设置日月轴
    private void setMonthXAxis(){
        XAxis xAxis = lineChart.getXAxis(); //获取x轴
        xAxis.setAxisMinimum(0f); //设置最小值
        xAxis.setAxisMaximum(12);  //设置最大值
        xAxis.setLabelCount(12); //设置显示个数
        xAxis.setDrawGridLines(false); //设置是否显示网格线
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //所在的位置
    }
    //设置y轴
    private void setYAxis(){
        YAxis axisLeft = lineChart.getAxisLeft(); //获取y轴
//        axisLeft.setAxisMaximum(26); //设置最大值
        axisLeft.setAxisMinimum(0); //设置最小值
        lineChart.getAxisRight().setEnabled(false); //设置折线图右边的轴是否显示
    }

    //启动折线图
    private void initData(List<HashMap<String, Object>> hashMapList,String time) {
        setYAxis();

        if(time.equals("month")){
            setMonthXAxis();
            lineChart.setExtraOffsets(24f,24f,24f,0f); //折线图左，上，右，下的偏移量
            setMonthChartData(hashMapList);
            return;
        }
        setDayXAxis();
        lineChart.setExtraOffsets(24f,24f,24f,0f); //折线图左，上，右，下的偏移量
        setDayChartData(hashMapList);
    }
    //设置日折线图数据
    public void setDayChartData(List<HashMap<String, Object>> hashMapList){
        List<YearDetail> list = new ArrayList<>();
        for(int i=1;i<32;i++){
            boolean isFind = false; //是否都没有
            YearDetail yearDetail=new YearDetail();
            for(int m=0;m<hashMapList.size();m++){
                Map<String,Object> map = hashMapList.get(m);
                if (Integer.parseInt(String.valueOf(map.get("day")))==i){
                    float d=Float.parseFloat(String.valueOf(map.get("money")));
                    yearDetail.setMonth(i);
                    yearDetail.setInmoney(d);
                    list.add(yearDetail);
                    isFind=true;
                }
            }
            if(!isFind){
                yearDetail.setMonth(i);
                yearDetail.setInmoney(0);
                list.add(yearDetail);
            }
        }

        List<Entry> yVals1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            yVals1.add(new Entry(list.get(i).getMonth(),list.get(i).getInmoney()));
        }
        LineDataSet set1=new LineDataSet(yVals1,"折线图");
        set1.setDrawFilled(true);
        set1.setFillColor(Color.WHITE);
        LineData lineData=new LineData(set1);
        lineChart.setData(lineData);
        lineChart.invalidate();
    }
    //设置月折线图数据
    public void setMonthChartData(List<HashMap<String, Object>> hashMapList){
        List<YearDetail> list = new ArrayList<>();
        for(int i=1;i<13;i++){
            boolean isFind = false; //是否都没有
            YearDetail yearDetail=new YearDetail();
            for(int m=0;m<hashMapList.size();m++){
                Map<String,Object> map = hashMapList.get(m);
                if (Integer.parseInt(String.valueOf(map.get("month")))==i){
                    float d=Float.parseFloat(String.valueOf(map.get("money")));
                    yearDetail.setMonth(i);
                    yearDetail.setInmoney(d);
                    list.add(yearDetail);
                    isFind=true;
                }
            }
            if(!isFind){
                yearDetail.setMonth(i);
                yearDetail.setInmoney(0);
                list.add(yearDetail);
            }
        }

        List<Entry> yVals1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            yVals1.add(new Entry(list.get(i).getMonth(),list.get(i).getInmoney()));
        }
        LineDataSet set1=new LineDataSet(yVals1,"折线图");
        set1.setDrawFilled(true);
        set1.setFillColor(Color.WHITE);
        LineData lineData=new LineData(set1);
        lineChart.setData(lineData);
        lineChart.invalidate();
    }


    //设置饼状图数据
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        //颜色的集合，按照存放的顺序显示
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.MATERIAL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.MATERIAL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);

        //设置折线
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        //设置线的长度
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.3f);
        //设置文字和数据图外显示
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        //百分比设置
        data.setValueFormatter(new PercentFormatter());
        //文字的颜色
        data.setValueTextSize(14f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        // 撤销所有的亮点
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }

    //list获取数据
    private void getList(List<ChartItemBean> mDatas){
        //设置适配器
        chartItemAdapter =new ChartItemAdapter( MonthChartActivity.this, mDatas);

        list_tb.setAdapter( chartItemAdapter );
    }

    // 设置ListView的点击事件，修改和删除
    private void ListItem() {
        list_tb.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChartItemBean clickBean = chartItemBeans.get(position);  //获取正在被点击的这条信息
                System.out.println("你点击了："+clickBean.getType());
//                Intent intent=new Intent( MainActivity.this,MessageActivity.class );
//                int Id=clickBean.getId();
//                int sImageId=clickBean.getsImageId();
//                String typeName=clickBean.getTypename();
//                float money=clickBean.getMoney();
//                String beizhu=clickBean.getBeizhu();

//                String time=clickBean.getTime();
//                int kind=clickBean.getKind();
//                intent.putExtra( "Id",String.valueOf( Id ));
//                intent.putExtra( "money",String.valueOf( money ) );
//                intent.putExtra( "sImageId",String.valueOf( sImageId ) );
//                intent.putExtra( "type",typeName );
//                intent.putExtra( "beizhu",beizhu );
//                intent.putExtra( "time",time );
//                intent.putExtra( "kind",String.valueOf( kind ) );
//                startActivity( intent );

            }
        } );
    }

}
